package com.bigtotoro.shuiyincamera.image;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigtotoro.shuiyincamera.BaseActivity;
import com.bigtotoro.shuiyincamera.R;
import com.bigtotoro.shuiyincamera.ShowMyArtsActivity;
import com.bigtotoro.shuiyincamera.adapter.CommonAdapter;
import com.bigtotoro.shuiyincamera.adapter.ViewHolder;
import com.bigtotoro.shuiyincamera.model.MyArt;
import com.bigtotoro.shuiyincamera.editimage.utils.BitmapUtils;
import com.bigtotoro.shuiyincamera.editimage.utils.FileUtil;
import com.bigtotoro.shuiyincamera.editimage.utils.Matrix3;
import com.bigtotoro.shuiyincamera.editimage.view.StickerItem;
import com.bigtotoro.shuiyincamera.editimage.view.StickerView;
import com.bigtotoro.shuiyincamera.editimage.view.TextStickerView;
import com.bigtotoro.shuiyincamera.editimage.view.imagezoom.ImageViewTouch;
import com.bigtotoro.shuiyincamera.editimage.view.imagezoom.ImageViewTouchBase;
import com.bigtotoro.shuiyincamera.util.MyUtils;
import com.bigtotoro.shuiyincamera.view.SelectPictureActivity;
import com.bigtotoro.shuiyincamera.util.FileUtils;
import com.bigtotoro.shuiyincamera.view.SquareImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import qiu.niorgai.StatusBarCompat;

/**
 * 图片加水印
 */
public class AddWaterMark02Activity extends BaseActivity implements View.OnClickListener, TextWatcher {
    private int imageWidth, imageHeight;//
    private LinearLayout model_content;

    private TextView tv_biaoqing,tv_wenzi,tv_tupian;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        checkInitImageLoader();//检测图片载入框架是否初始化
        setContentView(R.layout.activity_add_water_mark02);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.font_0));

        //添加友盟事件统计
        MyUtils.addUmengEvent(AddWaterMark02Activity.this,"img_add_watermark","图片加水印");


        DisplayMetrics metrics = getResources().getDisplayMetrics();
        imageWidth = metrics.widthPixels / 2;
        imageHeight = metrics.heightPixels / 2;

        getData();
        initView();
        initGrid();
        initData("stickers");
    }
    public static String filePath;// 需要编辑图片路径
    public String saveFilePath;// 生成的新图片路径
    private void getData() {
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        imageWidth = metrics.widthPixels;
        imageHeight = metrics.heightPixels;

        filePath = getIntent().getStringExtra("path"); //图片原始路径
        File outputFile = FileUtils.genEditFile();  //保存路径
        saveFilePath = outputFile.getAbsolutePath();

        loadImage(filePath);
    }

    private Bitmap mainBitmap;  //操作完成后获得的图片
    public ImageViewTouch mainImage; // 底部图层，放原始照片这一层
    private View backBtn;

    public StickerView mStickerView;// 贴图层View
    public TextStickerView mTextStickerView;//文本贴图显示View
    public StickerView mImageStickerView;//涂鸦模式画板

    private void initView() {
        tv_biaoqing = findViewById(R.id.tv_biaoqing);
        tv_wenzi = findViewById(R.id.tv_wenzi);
        tv_tupian = findViewById(R.id.tv_tupian);
        tv_biaoqing.setTextColor(getResources().getColor(R.color.white));
        tv_wenzi.setTextColor(getResources().getColor(R.color.white));
        tv_tupian.setTextColor(getResources().getColor(R.color.white));


        findViewById(R.id.btn_tietu).setOnClickListener(this);
        findViewById(R.id.btn_close).setOnClickListener(this);
        findViewById(R.id.btn_text).setOnClickListener(this);
        findViewById(R.id.btn_image).setOnClickListener(this);
        findViewById(R.id.btn_submit).setOnClickListener(this);
        model_content = findViewById(R.id.model_content);
        model_content.setVisibility(View.GONE);
        visibelMode = 1;


        mainImage = findViewById(R.id.main_image);// 页面正中的图片显示控件
        backBtn = findViewById(R.id.back);// 左上角退出按钮
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        /**
         * 真正操作图片的画布，都只存放在editImageActivity中
         * */
        mStickerView = (StickerView) findViewById(R.id.sticker_panel); //添加图片表情的画布
        mImageStickerView = (StickerView) findViewById(R.id.sticker_add_image); //添加图片表情的画布
        mTextStickerView = (TextStickerView) findViewById(R.id.text_sticker_panel);//添加文字画布
    }
    private List<String> pathList = new ArrayList<String>();// 图片路径列表

    private void initData(String folderPath) {  //获取assets中的图片，放入列表
            pathList.clear();
            try {
                String[] files = getAssets().list(folderPath);
                for (String name : files) {
                    if (name.lastIndexOf(".")>0){
                        pathList.add(folderPath + File.separator + name);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        commonAdapter.notifyDataSetChanged();
    }
    private List<String> mPhotoList = new ArrayList<>();
    private List<String> mSelectData = new ArrayList<>();
    private GridView grid;
    private CommonAdapter<String> commonAdapter;




    private void initGrid() {
         final DisplayImageOptions imageOption = new DisplayImageOptions.Builder()
                .cacheInMemory(true).showImageOnLoading(R.drawable.yd_image_tx)
                .build();// 下载图片显示
        grid = findViewById(R.id.grid);
        commonAdapter = new CommonAdapter<String>(this,
                pathList,
                R.layout.item_grid_item) {
            @Override
            public void convert(ViewHolder holder, String s) {
                SquareImageView iv_photo = holder.getConvertView().findViewById(R.id.iv_photo);
                ImageLoader.getInstance().displayImage("assets://" + s,
                        iv_photo, imageOption);
                    //选中改变
                    View item = holder.getConvertView().findViewById(R.id.item);
                    item.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int position = (int) v.getTag();
                            String path = pathList.get(position);
                            //
                            mStickerView.addBitImage(FileUtils.getImageFromAssetsFile(AddWaterMark02Activity.this,path));
                        }
                    });
                    item.setTag(holder.getPosition());
            }
        };
        grid.setAdapter(commonAdapter);
    }

    /**
     * 异步载入编辑图片
     */
    private LoadImageTask mLoadImageTask;

    public void loadImage(String filepath) {
        if (mLoadImageTask != null) {
            mLoadImageTask.cancel(true);
        }
        mLoadImageTask = new LoadImageTask();
        mLoadImageTask.execute(filepath);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String text = s.toString().trim();
        mTextStickerView.setText(text);//文字输入完成后，直接在画布上设置
    }


    /**
     * 导入文件图片任务
     * 为什么要搞一个异步载入图片，将图片转换成bitmap
     * 因为画布操作要用到bitmap?
     * 因为涉及到生成bitmap
     * 最后让mainbitmap == 生成的bitmap,各个子fragment可以直接调用
     * 这一步省不了。
     */
    private final class LoadImageTask extends AsyncTask<String, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... params) {  //设置显示在界面正中的图片的宽高，params[0]是图片路径
            Bitmap bitmap = BitmapUtils.getSampledBitmap(params[0], imageWidth,
                    imageHeight);
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap result) { //参数是AsyncTask的第三个参数
            //将获得的bitmap存储起来
            //限定选中了多张图片时，存储bitmap
            //result为空。。。

            changeMainBitmap(result, false);
        }
    }

    /**
     * @param newBit
     * @param needPushUndoStack
     */
    public void changeMainBitmap(Bitmap newBit, boolean needPushUndoStack) { //第二个参数是是否将图片压栈
        if (newBit == null)  //如果获取到的图片为空，返回
            return;
        if (mainBitmap == null || mainBitmap != newBit) {  //如果获取到的图片为空，返回
            mainBitmap = newBit;
            mainImage.setImageBitmap(mainBitmap);
            mainImage.setDisplayType(ImageViewTouchBase.DisplayType.FIT_TO_SCREEN);
        }
    }

    private SaveStickersTask mImageSaveTask;
    private void save() {
        if (mImageSaveTask != null) {
            mImageSaveTask.cancel(true);
        }
        //循环任务
        mImageSaveTask = new SaveStickersTask(this);
        mImageSaveTask.execute(mainBitmap); //获取当前mainImage的背景bitmap
    }

    /**
     * 保存贴图任务,三个保存方法合在一个方法里保存贴图数据
     */
    private final class SaveStickersTask extends com.bigtotoro.shuiyincamera.editimage.task.StickerTask {

        public SaveStickersTask(Activity activity) {
            super(activity);
        }

        @Override
        protected Bitmap doInBackground(Bitmap... bitmaps) {
            // System.out.println("保存贴图!");
            // 先把mainBitmap复制了一份到resultBit中
            //用canvas设置这个resultBit的bitmap作为背景画布，将文字绘制在上面
            Matrix touchMatrix = mainImage.getImageViewMatrix(); //touchMatrix是不变的
            Bitmap resultBit = Bitmap.createBitmap(bitmaps[0]).copy(
                    Bitmap.Config.ARGB_8888, true);
            Canvas canvas = new Canvas(resultBit);//画布是根据传入的bitmap生成的画布

            float[] data = new float[9];
            //将mainImage的矩阵数据复制到data数组中
            touchMatrix.getValues(data); // 底部图片变化记录矩阵原始数据
            Matrix3 cal = new Matrix3(data); // 辅助矩阵计算类
            Matrix3 inverseMatrix = cal.inverseMatrix(); // 计算逆矩阵
            Matrix m = new Matrix();
            m.setValues(inverseMatrix.getValues());

            int width = resultBit.getWidth();
            int height = resultBit.getHeight();

            /**两个方法分开执行，互不干扰**/
            handleImage2(canvas, m, width, height); //根据传入的bitmap生成的画布，根据mainImage计算出的矩阵
            handleImage(canvas, m); //根据传入的bitmap生成的画布，根据mainImage计算出的矩阵
            return resultBit;
        }

        /**
         * @param canvas //根据传入的bitmap生成的画布
         * @param m      //根据mainImage计算出的矩阵
         */
        @Override
        public void handleImage(Canvas canvas, Matrix m) { // 添加的图片水印
            /**
             * 保存贴图
             * **/
            LinkedHashMap<Integer, StickerItem> addItems02 = mStickerView.getBank();
            for (Integer id : addItems02.keySet()) {
                StickerItem item = addItems02.get(id);
                item.matrix.postConcat(m); //乘以底部图片变化矩阵
                canvas.drawBitmap(item.bitmap, item.matrix, null);
            }

            /**
             * 保存文字
             * **/
            float[] f = new float[9];
            m.getValues(f);
            int dx = (int) f[Matrix.MTRANS_X];
            int dy = (int) f[Matrix.MTRANS_Y];
            float scale_x = f[Matrix.MSCALE_X];
            float scale_y = f[Matrix.MSCALE_Y];
            canvas.save();
            canvas.translate(dx, dy);
            canvas.scale(scale_x, scale_y);
            //在文字画布上绘制文字图形
            //我需要的也正是文字画布,在每一张bitmap上使用文字画布合成一次图片，就是批量合成
            mTextStickerView.drawText(canvas, mTextStickerView.layout_x,
                    mTextStickerView.layout_y, mTextStickerView.mScale, mTextStickerView.mRotateAngle);
            canvas.restore(); //将文字绘制在了画布上

            /**
             * 保存图片水印
             * **/
            LinkedHashMap<Integer, StickerItem> addItems = mImageStickerView.getBank();// 获取每层贴图数据
            //拿到了所有的添加的图片水印
            for (Integer id : addItems.keySet()) {
                StickerItem item = addItems.get(id);
                item.matrix.postConcat(m);// 乘以底部图片变化矩阵,

//                item.matrix.preConcat(m);// 乘以底部图片变化矩阵,
                // postConcat相当于后乘，即 a=b×a
                //preConCat(b)相当于前乘,即 a=a×b
                canvas.drawBitmap(item.bitmap, item.matrix, null);
                //将水印图片保存到原图片中，每次获取到的都是最后刚刚添加的这个图片水印
            }
        }

        @Override
        public void handleImage2(Canvas canvas, Matrix m, int width, int height) {
        }

        @Override
        public void onPostResult(Bitmap result) {


            mTextStickerView.clearTextContent();
            mTextStickerView.resetView();
            mTextStickerView.setVisibility(View.GONE);

            mImageStickerView.clear();   //暂时不清空画布---2019/4/19
            mImageStickerView.setVisibility(View.GONE);

            changeMainBitmap(result, true);

            //保存图片
            doSaveImage();


        }
    }

    private SaveImageTask mSaveImageTask;

    protected void doSaveImage() {
        if (mSaveImageTask != null) {
            mSaveImageTask.cancel(true);
        }

        //在这里保存bitmap_list里的内容，取后一半的数据
        mSaveImageTask = new SaveImageTask();
        mSaveImageTask.execute(mainBitmap); //保存的是mainBitmap

    }

    private final class SaveImageTask extends AsyncTask<Bitmap, Void, Boolean> {
        private Dialog dialog;

        @Override
        protected Boolean doInBackground(Bitmap... params) {
            if (TextUtils.isEmpty(saveFilePath))  //saveFilePath通过EditImageActivity.start方法中传入的
                return false;
            return BitmapUtils.saveBitmap(params[0], saveFilePath);
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            dialog.dismiss();
        }

        @Override
        protected void onCancelled(Boolean result) {
            super.onCancelled(result);
            dialog.dismiss();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = getLoadingDialog(AddWaterMark02Activity.this, R.string.saving_image, false);
            dialog.show();
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            dialog.dismiss();
            if (result) { //图片保存成功
                //添加友盟事件统计
                MyUtils.addUmengEvent(AddWaterMark02Activity.this,"img_add_watermark_save","图片添加水印保存");
                Toast.makeText(AddWaterMark02Activity.this, getString(R.string.save_path, saveFilePath), Toast.LENGTH_LONG).show();
                //放入图片列表
                MyArt art = new MyArt();
                art.setHeight(imageHeight);
                art.setWidth(imageWidth);
                Long millis = System.currentTimeMillis();
                art.setCreate_time(millis + "");
                art.setPath(saveFilePath);
                art.setType(0); //加水印
                art.save();

                Intent intent = new Intent(AddWaterMark02Activity.this, ShowMyArtsActivity.class);
                intent.putExtra(EXTRA_OUTPUT, saveFilePath);
                intent.putExtra("create_time", art.getTrueCreateTime());
                intent.putExtra("width", imageHeight);
                intent.putExtra("height", imageWidth);
                intent.putExtra("type", "0");

                FileUtil.ablumUpdate(AddWaterMark02Activity.this, saveFilePath,0);//更新相册
                startActivity(intent);
                finish();
            } else {
                Toast.makeText(AddWaterMark02Activity.this, R.string.save_error, Toast.LENGTH_SHORT).show();
            }
        }
    }

    public static final String FILE_PATH = "file_path";
    public static final String EXTRA_OUTPUT = "extra_output";
    private void initStickerView() {
        mStickerView = findViewById(R.id.sticker_panel);
        mStickerView.setVisibility(View.VISIBLE);
    }

    private void initTextStickerView() {
        mTextStickerView = findViewById(R.id.text_sticker_panel);
        mTextStickerView.setVisibility(View.VISIBLE);
        mTextStickerView.setTextColor(getResources().getColor(R.color.font_3));
    }

    private void initImageStickerView() {
        mImageStickerView = findViewById(R.id.sticker_add_image);
        mImageStickerView.setVisibility(View.VISIBLE);
    }

    /**
     * 从相册选择编辑图片
     */
    private void selectFromAblum() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            openAblumWithPermissionsCheck();
        } else {
            openAblum();
        }
    }

    public static final int REQUEST_PERMISSON_SORAGE = 1;

    public static final int REQUEST_PERMISSON_CAMERA = 2;
    public static final int SELECT_GALLERY_IMAGE_CODE = 7;
    public static final int TAKE_PHOTO_CODE = 8;
    public static final int ACTION_REQUEST_EDITIMAGE = 9;

    private void openAblum() {
//         PictureSelector.create(this).openGallery(PictureMimeType.ofImage())
//                .previewVideo(true).selectionMode(PictureConfig.SINGLE).videoMinSecond(1).forResult(SELECT_GALLERY_IMAGE_CODE);
        startActivityForResult(new Intent(
                        this, SelectPictureActivity.class),
                SELECT_GALLERY_IMAGE_CODE);
    }

    private void openAblumWithPermissionsCheck() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    REQUEST_PERMISSON_SORAGE);
            return;
        }
        openAblum();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_PERMISSON_SORAGE
                && grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            openAblum();
            return;
        }//end if
    }

    private String mContent,mColor;
    int mAlpha;
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case SELECT_GALLERY_IMAGE_CODE://相册返回
                    handleSelectFromAblum(data);
                    break;
                case REQUEST_CODE_SETTING_TEXT://设置字体返回
                    mContent =  data.getStringExtra("content");
                    mColor =  data.getStringExtra("color");
                    mAlpha = data.getIntExtra("alpha",-1);
                    String h = Integer.toHexString(mAlpha);
                    if (h.length()<2){ //不足两位前面补0
                        h = "0"+h;
                    }
                    mTextStickerView.setText(mContent);
                    mTextStickerView.setTextColor(Color.parseColor("#"+h+mColor));
//                    mTextStickerView.getBackground().setAlpha(Integer.valueOf(mAlpha));
                    break;
            }
        }
    }

    private String path;

    private void handleSelectFromAblum(Intent data) {
        String filepath = data.getStringExtra("imgPath");
        path = filepath;
        /**
         * 拿到图片路径后，怎么将图片加载到mStickerView画布上？
         */
        Bitmap bitmap = BitmapUtils.getSampledBitmap(path, 200, 200);

        mImageStickerView.addBitImage(bitmap);//将从相册选取的图片加载到画布上

    }

    private static final int REQUEST_CODE_SETTING_TEXT= 3001;
    private int visibelMode = 0;//0已显示1未显示
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_tietu://表情水印
                tv_biaoqing.setTextColor(getResources().getColor(R.color.theme_gold));
                tv_wenzi.setTextColor(getResources().getColor(R.color.white));
                tv_tupian.setTextColor(getResources().getColor(R.color.white));
                if (visibelMode ==0){  //
                    model_content.setVisibility(View.GONE);
                    visibelMode = 1;
                }else if (visibelMode ==1){
                    model_content.setVisibility(View.VISIBLE);
                    visibelMode = 0;
                }
                initStickerView();
                break;
            case R.id.btn_text://文字水印
                tv_biaoqing.setTextColor(getResources().getColor(R.color.white));
                tv_wenzi.setTextColor(getResources().getColor(R.color.theme_gold));
                tv_tupian.setTextColor(getResources().getColor(R.color.white));
                initTextStickerView();
                startActivityForResult(new Intent(AddWaterMark02Activity.this,SettingTextActivity.class)
                ,REQUEST_CODE_SETTING_TEXT);
                break;
            case R.id.btn_image://图片水印
                tv_biaoqing.setTextColor(getResources().getColor(R.color.white));
                tv_wenzi.setTextColor(getResources().getColor(R.color.white));
                tv_tupian.setTextColor(getResources().getColor(R.color.theme_gold));
                initImageStickerView();
                selectFromAblum();  //选择输入图片，点击进入相册
                break;
            case R.id.btn_submit://保存
                save();
                break;
            case R.id.btn_close://关闭表情水印
            model_content.setVisibility(View.GONE);
                visibelMode = 1;
                break;
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("AddWaterMark02Activity");//统计页面
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("AddWaterMark02Activity");//统计页面
        MobclickAgent.onPause(this);
    }

}
